# -*- coding: utf-8 -*-
import cgi
import datetime
import wsgiref.handlers
import random

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
import views.TI as tiv
import models.trackingInfo as tim
from models.shippingOrder import SOModel
from models.manifest import ManifestModel

from models.enhancedModel import EnhancedModel as EM
import models.status as sm
import models.user as um

import decorator as dc
import helpers.maps as maps
import helpers.mail as mailHelper

class TIContr( webapp.RequestHandler ):

    @dc.decorate
    def get(self, action, *params):
        self.response.out.write(maps.getMapAPIScript())
        
        showArchival = self.request.get('archival') == 'True'
        
        permissionName = {"show1" : "tiShow",
                       "showAll" : "tiShow",
					   "showAllMine" : "tiShow",
                       "edit" : "tiEdit",
                       "delete" : "tiDelete",
                       "new": "tiNew",
                       "populate": "admin"
                       }
        
        if not um.UserModel.currentHasPermission(permissionName[action]):
          self.response.out.write("<font color=\"red\"><b>You have no rights to do this action.</b></font>")
          return

        if action == 'show1': # show1/id/number # DONE
            if not showArchival:
              query = EM.queryLatest(tim.TIModel, int(params[0]))
            else: 
              query = EM.queryAll(tim.TIModel, int(params[0]))
            for result in query:
                self.response.out.write(tiv.show1(um.UserModel.userRole(),result))
				
        elif action == 'showAll': # showAll/SOid/order_number # DONE
            if not showArchival:
              query = EM.queryLatest(tim.TIModel)
            else: 
              query = EM.queryAll(tim.TIModel)
			  
            response = query.filter('shippingOrder =', int(params[0])).fetch(1000)
            self.response.out.write(tiv.showAll(um.UserModel.userRole(),response, int(params[0])))
			
        elif action == 'showAllMine': # showAllMine/ # DONE
            if not showArchival:
              query = EM.queryLatest(tim.TIModel)
            else: 
              query = EM.queryAll(tim.TIModel)
			  
            response = query.filter('sender =', um.UserModel.userAcc().email()).fetch(1000)
            self.response.out.write(tiv.showAll(um.UserModel.userRole(),response, 666))
			
        elif action == 'edit': # edit/id/number
            query = EM.queryLatest(tim.TIModel, int(params[0]))
            result = query.get()
            self.response.out.write(tiv.edit(um.UserModel.userRole(),self.statusSelect(result.status), self.soSelect(result.shippingOrder), self.manifestSelect(result.manifest) ,result))

        elif action == 'new': # new # DONE
            orders = cgi.escape(self.request.get( 'orders' ))
            if not orders:
               orders = ''
            showError = self.request.get( 'error' )
            if showError=='SO':
                self.response.out.write("<font color=\"red\"><b>Invalid shipping order number!</b></font>")
            elif  showError=='manif':
                self.response.out.write("<font color=\"red\"><b>Manifest is required!</b></font>") 
            self.response.out.write(tiv.new(um.UserModel.userRole(),self.statusSelect(), self.soSelect(orders), self.manifestSelect() ))

        elif action == 'delete': # delete/id/numer
            ti = EM.queryLatest( tim.TIModel, ident=int(params[0])).get()
            if ti != None:
               self.response.out.write( tiv.delete( ti ))     
            else:
               self.response.out.write("<font color=\"red\"><b>This tracking information has been deleted before!</b></font>")
			   
        # # # just for debugging purposes    
        elif action == 'populate':
            #stats = ["shipped", "in transit", "delivered", "problem", "critical problem"]
            s = random.randrange(0, 4)
            u = []
            for (i,result) in enumerate(SOModel.all()):
               u.append(result.ident)
            if u == []:
               o = 0
            else:
               o = random.choice(u)
            #places = ["Wroclaw", "Warsaw", "Krakow", "Poznan", "Gdynia", "Gdansk", "Szczecin", "Opole", "Lodz", "Lublin", "Kielce", "Torun"]
            #p = random.choice(places)
            t = datetime.datetime.now()
            ti = tim.TIModel(status = s, time = t, shippingOrder = o)#, position = p)
            ti.put()
            query = tim.TIModel.all()
            self.response.out.write( "currently in datastore: " )
            self.response.out.write(query.count())
        # # #
        
    def post(self, action, *params):
        permissionName = {"show1" : "tiShow",
                       "showAll" : "tiShow",
                       "edit" : "tiEdit",
                       "delete" : "tiDelete",
                       "new": "tiNew"
                       }
        
        if not um.UserModel.currentHasPermission(permissionName[action]):
          self.response.out.write("<font color=\"red\"><b>You have no rights to do this action.</b></font>")
          return

        if action == 'new': # DONE
            sord = int(self.request.get('order'))
            so = SOModel.queryLatest(SOModel, ident=sord).get()
            err = False
            if not so:
               err = True

            if not err:
               newStatus = cgi.escape(self.request.get('status'))
               if newStatus == 'other':
                   newStatusTemplate = sm.StatusModel(
                     hidden = ('on' == self.request.get('hidden')),
                     isSuccess = ('on' == self.request.get('isSuccess')),
                     critical = ('on' == self.request.get('critical')),
                     description = self.request.get('description')
                   )
                   newStatusTemplate.put()
                   newStatus = newStatusTemplate.ident
               newStatus = int(newStatus)

               addr = cgi.escape(self.request.get('address'))
               if um.UserModel.userRole() == 'user':
                  addr = so.destination

               manif = self.request.get('manifest')
               if manif :
                 ti = tim.TIModel( 
                              shippingOrder = int(cgi.escape(self.request.get('order'))),
                              manifest = int(manif),
                              sender = um.UserModel.userAcc().email(),
                              status = newStatus,
                              positionText = addr,
                              position = maps.getGeoCoords(addr),
							  comment = cgi.escape(self.request.get('comment'))
                              )
               else:
                 self.redirect('/ti/new?error=manif')
               #should be replaced with datetime.now(helpers.std.CET_tzinfo)
               ti.time = datetime.datetime.now() + datetime.timedelta(hours = 2)
               ti.put()
               status = sm.StatusModel.queryLatest(sm.StatusModel, ti.status).get()
               if status.critical:
                 
                 mailHelper.sendOrderReport(so, (not status.hidden))
               else:
                 so.alreadyChecked = False
               so.put()
               self.redirect('/ti/show1/id/%d?done=True' % ti.ident)
            else:
               self.redirect('/ti/new?error=SO')
        
        elif action == 'edit':
            old = EM.queryLatest(tim.TIModel, int(params[0])).get()
            newStatus = self.request.get('status')
            if newStatus == 'other':
                newStatusTemplate = sm.StatusModel(
                    hidden = ('on' == self.request.get('hidden')),
                    isSuccess = ('on' == self.request.get('isSuccess')),
                    critical = ('on' == self.request.get('critical')),
                    description = self.request.get('description')
                )
                newStatusTemplate.put()
                status = newStatusTemplate.ident
            newStatus = int(newStatus)
            new = tim.TIModel( ident = old.ident,
                               status = newStatus,
                               shippingOrder = int(cgi.escape( self.request.get('order'))),
                               manifest = int(self.request.get('manifest')),
                               positionText = cgi.escape( self.request.get('address')),
                               position = maps.getGeoCoords(cgi.escape( self.request.get('address'))),
							   comment = cgi.escape(self.request.get('comment'))
                               )
            EM.deprecateOldVersion( new, old)
            self.redirect('/ti/show1/id/%d' % new.ident)

        elif action == 'delete': # 
            old = EM.queryLatest( tim.TIModel, ident=int(params[0])).get()
            ident = old.ident
            ident = old.ident
            if self.request.get('delete') == "NO":
              self.redirect('/ti/show1/id/%d' % ident)
            else:
              old.deleteInstance()
              self.redirect('/ti/show1/id/%d?archival=True&done=True' % ident)

    def statusSelect(self, selected=-1): 
        if um.UserModel.userRole()=='user': # User ma tylko jeden status: Confirmation of delivery
          query = EM.queryLatest(sm.StatusModel)
          s = query.filter('description =', 'Confirmation of delivery').get()
          if s != None:
            return '<input type="hidden" name="status" value="%d" />' % int(s.ident)
          else:
            newStatusTemplate = sm.StatusModel(
                    hidden = ('on' == False),
                    isSuccess = ('on' == True),
                    critical = ('on' == False),
                    description = 'Confirmation of delivery'
                )
            newStatusTemplate.put()
            return '<input type="hidden" name="status" value="%d" />' % int(newStatusTemplate.ident)

        # Wybór statusu dla pozostałych
        select = ''' 
            <script>
                function toggleOther(sel)
                {
                    var div = document.getElementById('other')
                    if ( sel.options[sel.selectedIndex].value == "other" )
                    {
                        div.style.display = "block"
                    }
                    else
                    {
                        div.style.display = "none"
                    }
                }
            </script>
        ''' 
        select += '<select name="status" onchange="toggleOther(this);" id="theselect">'
        query = EM.queryLatest(sm.StatusModel)
        for result in query:
          if result.description != 'Confirmation of delivery':
            if result.ident == selected:
                curSelected = 'selected' 
            else:
                curSelected = ''
            select += '<option value="%d" %s>%s</option>' % (result.ident, curSelected, result.description)
        if um.UserModel.userRole()=='admin': # tylko admin może wybrać other
          select += '<option value="other">Other...</option>'
        select += '</select>'
        if um.UserModel.userRole()=='admin':
          select += '''
            <div id="other" style='margin: 5px; padding: 5px; border: 1px solid #cccccc; display: none'>
                <input type='checkbox' name='hidden'> Hidden <br /><input type='checkbox' name='critical'> Critical<br /> <input type='checkbox' name='isSuccess'> Is Success? <br /> Description <input type='text' name='description' value=''>
            </div>
            <script>
                 toggleOther(document.getElementById('theselect'))
            </script>
          '''
        return select
        
    def soSelect (self, selected = -1):
        select = '<select name="order" onchange="toggleOther(this);" id="theselect">'
        query = EM.queryLatest(SOModel)
        if um.UserModel.userRole()=='user':
           query.filter('recipient =', um.UserModel.userId())
           query.filter('finished =', True)
           q = query.get()
           if q == None:
             return ''

        for result in query:
            if result.ident == selected:
                curSelected = 'selected' 
            else:
                curSelected = ''
            soView = "%d (%s - %s)" % (result.ident, result.origin, result.destination)
            select += '<option value="%d" %s>%s</option>' % (result.ident, curSelected, soView)
        select += '</select>'
        return select
            
    def manifestSelect (self, selected = -1):
        if um.UserModel.userRole()=='user': 
           return ''
        select = '<select name="manifest" onchange="toggleOther(this);" id="theselect">'
        query = EM.queryLatest(ManifestModel)
        for result in query:
            if result.ident == selected:
                curSelected = 'selected' 
            else:
                curSelected = ''
            select += '<option value="%d" %s>%d</option>' % (result.ident, curSelected, result.ident)
        select += '</select>'
        return select
